/*
 * Copyright 2003-2005 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

using System;


namespace argot
{
	
	public class TypeConstructorAuto 
	:TypeConstructor
	{
		private System.Type _clss;
		
		public TypeConstructorAuto(System.Type clss)
		{
			_clss = clss;
		}
		
		public virtual System.Object Construct(System.Object[] objs)
		{
			System.Object[] objects = new System.Object[objs.Length];
			for (int x = 0; x < objs.Length; x++)
			{
				objects[x] = (objs[x]);
			}
			
			System.Reflection.ConstructorInfo[] constructors = _clss.GetConstructors();
			
			for (int x = 0; x < constructors.Length; x++)
			{
				if (constructors[x].GetParameters().Length == objects.Length)
				{
					bool found = true;

					System.Reflection.ParameterInfo[] paramInfo = constructors[x].GetParameters();

					for (int y = 0; y < paramInfo.Length; y++)
					{
						if (objects[y] != null)
							if (!paramInfo[y].ParameterType.IsInstanceOfType(objects[y]))
							{
								if (objects[y] == null)
									continue;
																
								found = false;
								break;
							}
					}
					
					if (found == false)
						continue;
					
					try
					{
						return constructors[x].Invoke(objects);
					}
					catch (System.ArgumentException e)
					{
						throw new TypeException("TypeReaderAuto:" + e.ToString());
					}
					catch (System.Exception e)
					{
						throw new TypeException("TypeReaderAuto:" + e.ToString());
					}

				}
			}
			
			throw new TypeException("TypeReaderAuto: No valid constructors found." + _clss.FullName);
		}
	}
}